package com.aha.dataanalyzeandview.config;


import com.aha.dataanalyzeandview.entity.qdii.QDIIFoundationPremiumEstimationEntity;
import com.aha.dataanalyzeandview.entity.wxrobot.WxRobotSettingsEntity;
import com.aha.dataanalyzeandview.jsoup.ParsePremiumQueryPageHTML;
import com.aha.dataanalyzeandview.quartz.QuartzJobUtils;
import com.aha.dataanalyzeandview.quartz.WxRobotSendMsgJob;
import com.aha.dataanalyzeandview.service.IQdiiFoundationService;
import com.aha.dataanalyzeandview.service.IWxRobotService;
import com.aha.dataanalyzeandview.service.impl.QdiiFoundationServiceImpl;
import com.aha.dataanalyzeandview.utils.DateUtils;
import com.aha.dataanalyzeandview.utils.MyStringUtils;
import com.aha.dataanalyzeandview.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class ScheduledService {

    @Autowired
    private IQdiiFoundationService qdiiFoundationService;


    @Autowired
    private QuartzJobUtils quartzJobUtils;

    @Autowired
    private IWxRobotService wxRobotService;

    /**
     * 项目启动后，将job
     */
    @PostConstruct
    public void quartzInit() {

        // 查询定义的微信发信机器人的任务
        List<WxRobotSettingsEntity> wxRobotSettingsEntities = wxRobotService.queryWxRobotSettingsInfo(new HashMap<>());

        for (WxRobotSettingsEntity w : wxRobotSettingsEntities) {
            wxRobotJobReset(w);
        }
    }


    /**
     * 添加微信机器人定时任务
     *
     * @param w
     */
    public void wxRobotJobReset(WxRobotSettingsEntity w) {
        // 如果是启用状态才生效
        String jobName = "job-" + w.getId();
        if (w.getStatus() == 1) {
            Map<String, Object> map = ObjectUtils.objectToMap(w);
            log.info("启动微信机器人，机器人发送消息的参数：" + map.toString());
            String strWeekdays = DateUtils.weekdays2StrWeekdays(w.getWeekday());
            String jobTime = String.format("0 %s %s ? * %s", w.getSendTimeMinute(), w.getSendTimeHour(), strWeekdays);
//            String jobTime = String.format("0/1 * * ? * MON,TUE,WED,THU,FRI", w.getSendTimeMinute(), w.getSendTimeHour(), w.getWeekday());
            log.info("启动微信机器人，机器人的唤醒时机：" + jobTime);
            quartzJobUtils.deleteJob(jobName, "test");
            quartzJobUtils.addJob(WxRobotSendMsgJob.class, jobName, "test", jobTime, map);
//                quartzJobUtils.addJob(WxRobotSendMsgJob.class, jobName, "test", "26 * * * * ?", map);
        } else {
            log.info("关闭微信机器人： " + jobName);
            quartzJobUtils.deleteJob(jobName, "test");
        }
    }

    /**
     * 添加微信机器人定时任务
     *
     * @param id
     */
    public void closeWxRobotJobReset(Integer id) {
        // 如果是启用状态才生效
        String jobName = "job-" + id;

        List<Map<String, Object>> maps = quartzJobUtils.queryAllJob();
        for (Map<String, Object> map : maps) {
            if(jobName.equals(map.get("jobName"))){
                log.info("关闭微信机器人发信任务，机器人的id是：" + jobName);
                quartzJobUtils.deleteJob(jobName, "test");
            }
        }
    }


    /**
     * 初始化数据
     */
    @PostConstruct
    public void initData() {
        ThreadPoolExecutor pool = MyThreadPoolExecutor.buildThreadPool();
        pool.submit(() -> {
            QDIIFoundationPremiumEstimationEntity qdii = qdiiFoundationService.queryQdiiDataLastDate();
            Date yesteday = DateUtils.getLastNDayDate(1);
            log.info("开始初始化qdii数据。。。");
            // 24小时内没有数据导入，就执行数据导入
            if (qdii.getCreateDate() != null && yesteday.getTime() > qdii.getCreateDate().getTime()) {
                collectQdiiFoundationData();
            }
        });
    }


    /**
     * 每天晚上18:00执行一次
     */
    @Scheduled(cron = "0 0 */18 * * *")
    public void collectQdiiFoundationData() {

        String url = "https://www.palmmicro.com/woody/res/lofcn.php";
        // 获取tr中所有的td的数据
        List<List<String>> res = ParsePremiumQueryPageHTML.getTrTdValuesToList(url, 2);
        List<List<String>> res2 = ParsePremiumQueryPageHTML.getTrTdValuesToList(url, 3);

        List<QDIIFoundationPremiumEstimationEntity> qdiiList = new ArrayList<>();

        for (List<String> stringList : res2) {
            QDIIFoundationPremiumEstimationEntity qdii = new QDIIFoundationPremiumEstimationEntity();
//            代码 净值 官方估值 溢价 参考估值 溢价 实时估值 溢价
            // 如果字段中包含中文，直接跳过
            if (stringList != null && stringList.size() > 0 && MyStringUtils.isContainChinese(stringList.get(0))) {
                continue;
            }
            qdii.setFoundationCode(stringList.get(0))
                    .setCurrentPrice(Float.valueOf(stringList.get(1)))
                    .setOfficialEstimationValue(Float.valueOf(stringList.get(2)))
                    .setOfficialEstimationPremiumRate(Float.valueOf(stringList.get(3).replace("%", "")) / 100)
                    .setReferenceEstimationValue(Float.valueOf(stringList.get(4)))
                    .setReferenceEstimationPremiumRate(Float.valueOf(stringList.get(5).replace("%", "")) / 100);
            if (stringList.size() > 6) {
                qdii.setRealTimeEstimationValue(Float.valueOf(stringList.get(6)));
            }
            if (stringList.size() > 7) {
                qdii.setRealTimeEstimationPremiumRate(Float.valueOf(stringList.get(7).replace("%", "")) / 100);
            }
            qdiiList.add(qdii);
        }

        for (List<String> stringList : res) {
            if (stringList != null && stringList.size() > 0 && MyStringUtils.isContainChinese(stringList.get(0))) {
                continue;
            }
            for (QDIIFoundationPremiumEstimationEntity qdii : qdiiList) {
                // 如果基金代码一样的话，合并数据, 设置基金的名称
                if (qdii.getFoundationCode().equals(stringList.get(0))) {
                    qdii.setFoundationName(stringList.get(5));
                    log.info("获取基金数据： " + qdii.toString());
                    break;
                }
            }
        }

        int size = qdiiFoundationService.batchAddQdiiFoundationData(qdiiList);
        log.info("抓取基金数据并存储到数据库的数据条数: " + size);

    }
}
